package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.sms.vo.SkuSaleVO;
import com.atguigu.gmall.pms.dao.*;
import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.pms.fegin.GmalSmsClient;
import com.atguigu.gmall.pms.service.*;
import com.atguigu.gmall.pms.vo.BaseAttrVO;
import com.atguigu.gmall.pms.vo.SkuInfoVO;
import com.atguigu.gmall.pms.vo.SpuInfoVO;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.core.bean.PageVo;
import com.atguigu.core.bean.Query;
import com.atguigu.core.bean.QueryCondition;

import org.springframework.util.CollectionUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescDao spuInfoDescDao;

    @Autowired
    private ProductAttrValueService productAttrValueService;//注入sercie保存
    @Autowired
    private SkuInfoDao skuInfoDao;

    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private GmalSmsClient gmalSmsClient;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Value("${item.rabbitmq.exchange}")
    private String EXCHANGE_NAME;

    @Override
    public PageVo queryPage(QueryCondition params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageVo(page);
    }
    //查询商品信息
    @Override
    public PageVo querySpuInfo(QueryCondition condition, Long catId) {
        QueryWrapper<SpuInfoEntity> wrapper=new QueryWrapper<>();
        //封装其他条件
        if(catId!=0){
            wrapper.eq("catalog_id",catId);
        }

        //判断关键字是否为空
        String key=condition.getKey();
        if(StringUtils.isNotBlank(key)){
            wrapper.and(t->t.like("spu_name",key).or().like("id", key));//and代表拼接
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(condition),
                wrapper
        );

        return new PageVo(page);

    }

    //spu的大保存
    @Override
    @GlobalTransactional
    public void bigSave(SpuInfoVO spuInfoVO) {
        //1、保存spu相关的三张表
        //1.1、保存pms_spu_info
        spuInfoVO.setCreateTime(new Date());
        spuInfoVO.setUodateTime(spuInfoVO.getCreateTime());
        //spuInfoVO.setSpuImages();
        this.save(spuInfoVO);
        Long spuId = spuInfoVO.getId();
        //1.2、保存pms_spu_info_desc
        List<String> spuImages = spuInfoVO.getSpuImages();
        if(!CollectionUtils.isEmpty(spuImages)){
            SpuInfoDescEntity spuInfoDescEntity=new SpuInfoDescEntity();
            spuInfoDescEntity.setSpuId(spuId);
            spuInfoDescEntity.setDecript(StringUtils.join(spuImages,","));
            this.spuInfoDescDao.insert(spuInfoDescEntity);
        }

        //1.3、保存pms_product_attr_value
        List<BaseAttrVO> baseAttrs = spuInfoVO.getBaseAttrs();
        if(!CollectionUtils.isEmpty(baseAttrs)){

            List<ProductAttrValueEntity> attrValueEntities = baseAttrs.stream()
                    .map(baseAttrVO ->{
                        ProductAttrValueEntity attrValueEntity=baseAttrVO;
                        attrValueEntity.setSpuId(spuId);
                        return attrValueEntity;
                    }).collect(Collectors.toList());//装换为另一个集合
            productAttrValueService.saveBatch(attrValueEntities);//如果不为空，在进行批量保存
        }

        //2、保存sku的三张表

        List<SkuInfoVO> skus = spuInfoVO.getSkus();
        if(CollectionUtils.isEmpty(skus)){
            //如果skus为空，直接返回
            return ;
        }
        skus.forEach(skuInfoVO -> {
            //2.1、保存pms_sku_info
            skuInfoVO.setSpuId(spuId);
            skuInfoVO.setSkuCode(UUID.randomUUID().toString());
            skuInfoVO.setBrandId(spuInfoVO.getBrandId());
            skuInfoVO.setCatalogId(spuInfoVO.getCatalogId());
            //设置图片
            List<String> images=spuInfoVO.getSpuImages();
            //判断图片是否为空，设置默认图片,如果有默认图片就使用规模人的，如果没有，就需要自己使用上传的第一个
            if(!CollectionUtils.isEmpty(images)){
                skuInfoVO.setSkuDefaultImg(StringUtils.isNotBlank(skuInfoVO.getSkuDefaultImg())?skuInfoVO.getSkuDefaultImg():images.get(0));
            }
            skuInfoDao.insert(skuInfoVO);
            //2.2、保存pms_sku_images
            Long skuId=skuInfoVO.getSkuId();
            //先判断图片不能为空时，才进行保存
            if(!CollectionUtils.isEmpty(images)){
                //把图片装换为对象集合才能进行批量保存
                List<SkuImagesEntity> skuImagesEntities = images.stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setImgUrl(image);
                    skuImagesEntity.setSkuId(skuId);
                    //设置是否为默认图片,可以通过之前设置的默认图片和当前的图片进行地址对比确定是否为默认图片
                    skuImagesEntity.setDefaultImg(org.apache.commons.lang3.StringUtils.equals(skuInfoVO.getSkuDefaultImg(), image) ? 1 : 0);
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                //批量保存
                this.skuImagesService.saveBatch(skuImagesEntities);
            }

            //2.3、保存pms_sal_attr_value
            List<SkuSaleAttrValueEntity> saleAttrs = skuInfoVO.getSaleAttrs();
            if(!CollectionUtils.isEmpty(saleAttrs)){
                //循环遍历设置sku的ID
                saleAttrs.forEach(skuSaleAttrValueEntity -> skuSaleAttrValueEntity.setSkuId(skuId));
                //批量保存属性
                this.skuSaleAttrValueService.saveBatch(saleAttrs);
            }

            //3、保存sms_下面的三张表.保存营销的三张表，通过远程调用sm的保存
            SkuSaleVO skuSaleVO=new SkuSaleVO();
            BeanUtils.copyProperties(skuInfoVO,skuSaleVO);
            skuSaleVO.setSkuId(skuId);
            this.gmalSmsClient.saveSkuSale(skuSaleVO);

            sendMsg("insert",spuId);

        });

    }

    //消息中间件使用
    private void sendMsg(String type,Long spuId){
        //1、注入模板

        //2、申明交换机

        //3、使用
        try {
            this.amqpTemplate.convertAndSend(EXCHANGE_NAME,"item."+type,spuId);
        }catch (Exception e) {
            //System.out.println("{}商品消息发送异常，商品id：{}", type,spuId, e);
            e.printStackTrace();
        }
    }
}